const express = require('express');
const router = express.Router();
const { pool } = require('../config/db');
const auth = require('../middleware/auth');

// 复制课表 - 从一个班级复制到另一个班级
router.post('/', auth, async (req, res) => {
  try {
    // 检查权限
    if (req.user.role !== 'admin') {
      return res.status(403).json({ message: '权限不足' });
    }
    
    const { sourceClassId, targetClassId, startWeek, endWeek } = req.body;
    
    // 参数验证
    if (!sourceClassId || !targetClassId) {
      return res.status(400).json({ message: '缺少必要参数' });
    }
    
    if (sourceClassId === targetClassId) {
      return res.status(400).json({ message: '源班级和目标班级不能相同' });
    }
    
    // 验证周次范围
    if (!startWeek || !endWeek || startWeek > endWeek || startWeek < 1 || endWeek > 20) {
      return res.status(400).json({ message: '周次范围无效' });
    }
    
    // 1. 获取源班级的课表数据
    const [sourceTimetables] = await pool.query(
      `SELECT * FROM timetables WHERE classId = ?`,
      [sourceClassId]
    );
    
    if (sourceTimetables.length === 0) {
      return res.status(404).json({ message: '源班级没有课表数据' });
    }
    
    // 2. 删除目标班级在指定周次范围内的现有课表数据
    await pool.query(
      `DELETE FROM timetables 
       WHERE classId = ? 
       AND ((startWeek BETWEEN ? AND ?) 
       OR (endWeek BETWEEN ? AND ?) 
       OR (startWeek <= ? AND endWeek >= ?))`,
      [targetClassId, startWeek, endWeek, startWeek, endWeek, startWeek, endWeek]
    );
    
    // 3. 复制源班级的课表数据到目标班级
    let insertCount = 0;
    for (const timetable of sourceTimetables) {
      // 调整周次范围，确保在指定范围内
      const newStartWeek = Math.max(timetable.startWeek, startWeek);
      const newEndWeek = Math.min(timetable.endWeek, endWeek);
      
      // 只复制周次范围有重叠的课程
      if (newStartWeek <= newEndWeek) {
        await pool.query(
          `INSERT INTO timetables 
           (classId, courseId, teacherId, roomId, day, period, startWeek, endWeek, semester) 
           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
          [
            targetClassId,
            timetable.courseId,
            timetable.teacherId,
            timetable.roomId,
            timetable.day,
            timetable.period,
            newStartWeek,
            newEndWeek,
            timetable.semester
          ]
        );
        insertCount++;
      }
    }
    
    res.status(200).json({ 
      message: '课表复制成功', 
      count: insertCount 
    });
    
  } catch (error) {
    console.error('复制课表错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

module.exports = router;